package com.liu.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.security.mapper.DUserMapper;
import com.liu.security.pojo.DUser;
import com.liu.security.pojo.Permission;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.DuplicateFormatFlagsException;
import java.util.List;

/**
 * Created by shi860715@126.com
 * Date 2021/8/14 10:22
 * 安全验证框架  数据库联动
 */
@Service("userDetailsService")
@Slf4j
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    DUserMapper  dUserMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<DUser> query = new QueryWrapper<DUser>();
        query.eq("username",username);

       DUser  user  = dUserMapper.selectOne(query);
       if(user == null){
           throw  new UsernameNotFoundException("用户不存在！");
       }
        user= dUserMapper.getUserPermission(user.getId());
       Collection<SimpleGrantedAuthority> authlist = new ArrayList<>();
        for (Permission e: user.getPermissions()){
            if(
                    !StringUtils.isEmpty(e.getPermission())){
                authlist.add(new SimpleGrantedAuthority(e.getPermission()));
                log.info(e.getPermission());
            }

        }
        System.out.println(authlist);
        UserDetails userDetails =  new User(username,user.getPassword(),authlist);
        return userDetails;
    }
}
